
/**
 *  handles calls from ajax_link's
 *
 *  @param [sUrl] url of resource
 *  @param [sUpdate] id of element to update
 *  @param [sHandler] optional name of handler function
 *
 */

function smutty_ajaxLink( sUrl, sUpdate, sHandler ) {
	smutty_ajaxCall( sUrl, sUpdate, sHandler, null );
}

/**
 *  handles calls from ajax_form's
 *
 *  @param [oForm] the form to submit
 *  @param [sUrl] the url of the resource
 *  @param [sUpdate] id of element to update
 *  @param [sHandler] optional custom handler function
 *
 */

function smutty_ajaxForm( oForm, sUrl, sUpdate, sHandler ) {
	smutty_ajaxCall( sUrl, sUpdate, sHandler, Form.serialize(oForm) );
}

/**
 *  makes an ajax call.
 *
 *  @param [sUrl] the url resource
 *  @param [sUpdate] the element id to receive the response
 *  @param [sHandler] optional function to handle the response
 *  @param [sParameters] any params for the request
 *  @param [sFeedback] optional id of element for feedback
 *
 */

function smutty_ajaxCall( sUrl, sUpdate, sHandler, sParameters, sFeedback ) {

	// get a reference to the handler function
	var rHandler = null;
	if ( !sHandler )
		sHandler = 'smutty_ajaxUpdate';
	eval( 'rHandler = ' + sHandler + ';' );

	new Ajax.Request(
		sUrl,
		{
			parameters: sParameters,
			onLoading: function() {
				if ( sFeedback )
					smutty_ajaxFeedback( sFeedback, 'Updating...' );
			},
			onComplete: function( oRequest ) {
				if ( sFeedback )
					smutty_ajaxFeedback( sFeedback, '' );
				rHandler( oRequest, sUpdate );
			},
			onFailure: function( oRequest ) {
				alert( 'Ajax error!' );
			}
		}
	);

}

/**
 *  sets a feedback element with some content.  if you want
 *  to clear the feedback then just pass the empty string.
 *
 *  @param [sId] id of element
 *  @param [sContent] the contect to set
 *
 */

function smutty_ajaxFeedback( sId, sContent ) {
	$( sId ).innerHTML = sContent ? '<img src="' + BASE_URL + '/smutty/resource/images/updating.gif" ' +
		' alt="Updating" /> ' + sContent : '';
}

/**
 *  this is the default handles for ajax queries and just
 *  updates the element id specified by sUpdate with the
 *  response of the query
 *
 *  @param [oRequest] the request object
 *  @param [sUpdate] id of element to update
 *
 */

function smutty_ajaxUpdate( oRequest, sUpdate ) {

	var eElem = $(sUpdate);

	eElem.innerHTML = oRequest.responseText;

	// javascript isn't run when replacing innerHTML
	var text = new String( oRequest.responseText )
	var re = new RegExp( '<script.*?>(.*?)</script>', 'g' );
	var match = text.match( re );

	for ( var i=0; i<match.length; i++ ) {
		var script = match[ i ];
		script = script.replace( new RegExp('<script.*?>'), '' );
		script = script.replace( new RegExp('</script>'), '' );
		eval( script );
	}

}

/**
 *  a function that just does nothing.  used as a function when
 *  no action is required (but we can still pass a valid function
 *  to whatever wants it.
 *
 */

function smutty_doNothing() {
	return true;
}
